package cn.luckdou.commons.ucpaas;

import cn.luckdou.commons.utils.JsonUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URI;
import java.util.*;

public class UcpaasUtil {
    public static final String accountSid = "dc6c93a649062dc8b7a591027a789b51";
    public static final String version = "2014-06-30";
    public static final String authToken = "26e3a2918092da535095b2550a32bad7";
    public static final String appId = "e8c1578fa8ae42488b89064d3057c4d8";

    private static CloseableHttpClient httpClient;
    static {
        httpClient = HttpClients.createDefault();
    }
    // 把HttpClient封闭成单例的
    public static CloseableHttpClient getHttpClient() {
        if (httpClient == null) {
            httpClient = HttpClients.createDefault();
            return httpClient;
        }
        return httpClient;
    }


    //封装GET请求方法
    public static String doGet(String url, float second) {
        HttpGet httpGet = new HttpGet();
        httpGet.setHeader("Accept", "application/json");
        httpGet.setHeader("Content-Type", "application/json;charset=utf-8");
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.87 Safari/537.36");
        CloseableHttpResponse response = null;
        //设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout((int) (1000 * second)).setConnectTimeout((int) (1000 * second)).build();
        httpGet.setConfig(requestConfig);
        try {
            httpGet.setURI(new URI(url));
            response = getHttpClient().execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            close();
        }
    }
    //封装POST请求方法
    public static String Post(String url, String content,String timestamp) {
        HttpPost httpPost = new HttpPost(url);
        try {
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
            String auth = new EncryptUtil().base64Encoder(accountSid + ":" + timestamp);
            httpPost.setHeader("Authorization", auth);
            BasicHttpEntity requestBody = new BasicHttpEntity();
            requestBody.setContent(new ByteArrayInputStream(content.getBytes("UTF-8")));
            requestBody.setContentLength(content.getBytes("UTF-8").length);
            httpPost.setEntity(requestBody);
            HttpResponse  response = getHttpClient().execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    return EntityUtils.toString(resEntity, "UTF-8");
                }
            }
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            close();
        }
    }

    //通用关流方法
    public static void close() {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
            } finally {
                httpClient = null;
            }
        }
    }

    public static String templateSMS(TemplateSMS templateSMS) {
        String result = "";
        EncryptUtil encryptUtil = new EncryptUtil();
        String timestamp = DateUtil.dateToStr(new Date(), DateUtil.DATE_TIME_NO_SLASH);// 时间戳
        String signature =getSignature(accountSid,authToken,timestamp,encryptUtil);
        String url="https://api.ucpaas.com/"+version+"/Accounts/"+accountSid+"/"+"Messages/templateSMS"+"?sig="+signature;
        templateSMS.setAppId(appId);
        String body = JsonUtils.objectToJson(templateSMS);
        body="{\"templateSMS\":"+body+"}";
        result=Post(url,body,timestamp);
        return result;
    }
    public static String getSignature(String accountSid, String authToken,String timestamp,EncryptUtil encryptUtil) {
        try{
            String sig = accountSid + authToken + timestamp;
            String signature = encryptUtil.md5Digest(sig);
            return signature;
        }catch (Exception e){
            return null;
        }
    }

    public static void main(String[] args) {
//        TemplateSMS t=new TemplateSMS();
//        t.setParam("1234");
//        t.setTemplateId("154251");
//        t.setTo("17610078096");
//        String s = templateSMS(t);
//        System.out.println(s);
//
        String s = doGet("http://www.dlayer.cn/r/sendCode.php?phone=18401498568", 60f);
        System.out.println(s);

    }

}
